import { useUserStore } from '@/stores/user'
import { ElMessage } from 'element-plus'

// 白名单路由（无需登录即可访问）
const whiteList = ['/login', '/404']

// 权限路由映射
const permissionRoutes = {
  // 用户管理
  '/users': ['user:view'],
  '/users/list': ['user:view'],
  '/users/roles': ['role:view'],
  
  // 人力资源
  '/hr': ['hr:view'],
  '/hr/employees': ['hr:employee:view'],
  '/hr/attendance': ['hr:attendance:view'],
  '/hr/salary': ['hr:salary:view'],
  
  // 采购管理
  '/purchase': ['purchase:view'],
  '/purchase/suppliers': ['purchase:supplier:view'],
  '/purchase/orders': ['purchase:order:view'],
  '/purchase/receiving': ['purchase:receiving:view'],
  
  // 仓库管理
  '/warehouse': ['warehouse:view'],
  '/warehouse/inventory': ['warehouse:inventory:view'],
  '/warehouse/inbound': ['warehouse:inbound:view'],
  '/warehouse/outbound': ['warehouse:outbound:view'],
  '/warehouse/stocktaking': ['warehouse:stocktaking:view'],
  
  // 销售管理
  '/sales': ['sales:view'],
  '/sales/customers': ['sales:customer:view'],
  '/sales/orders': ['sales:order:view'],
  '/sales/pos': ['sales:pos:view'],
  
  // 财务管理
  '/finance': ['finance:view'],
  '/finance/accounts': ['finance:account:view'],
  '/finance/vouchers': ['finance:voucher:view'],
  '/finance/reports': ['finance:report:view'],
  
  // 基础档案
  '/archives': ['archives:view'],
  '/archives/products': ['archives:product:view'],
  '/archives/bom': ['archives:bom:view'],
  
  // 报表中心
  '/reports': ['report:view'],
  '/reports/standard': ['report:standard:view'],
  '/reports/custom': ['report:custom:view'],
  
  // 透视分析
  '/pivot': ['pivot:view'],
  '/pivot/analysis': ['pivot:analysis:view'],
  '/pivot/drill': ['pivot:drill:view'],
  
  // AI分析
  '/ai': ['ai:view'],
  '/ai/prediction': ['ai:prediction:view'],
  '/ai/anomaly': ['ai:anomaly:view'],
  
  // 低代码开发
  '/lowcode': ['lowcode:view'],
  '/lowcode/forms': ['lowcode:form:view'],
  '/lowcode/workflows': ['lowcode:workflow:view'],
  
  // 数据模型
  '/datamodel': ['datamodel:view'],
  '/datamodel/entities': ['datamodel:entity:view'],
  '/datamodel/relations': ['datamodel:relation:view'],
  
  // 系统配置
  '/system': ['system:view'],
  '/system/settings': ['system:setting:view'],
  '/system/monitor': ['system:monitor:view']
}

// 角色路由映射
const roleRoutes = {
  // 系统管理员 - 拥有所有权限
  'admin': ['*'],
  
  // 企业管理员 - 除系统配置外的所有权限
  'enterprise_admin': [
    'user:*', 'hr:*', 'purchase:*', 'warehouse:*', 'sales:*', 
    'finance:*', 'archives:*', 'report:*', 'pivot:*', 'ai:*', 
    'lowcode:*', 'datamodel:*'
  ],
  
  // 部门经理 - 部门相关权限
  'department_manager': [
    'hr:view', 'hr:employee:view', 'hr:attendance:view',
    'purchase:view', 'purchase:order:view',
    'sales:view', 'sales:customer:view', 'sales:order:view',
    'report:view', 'report:standard:view'
  ],
  
  // 业务员工 - 基础业务权限
  'employee': [
    'sales:view', 'sales:customer:view', 'sales:order:view',
    'warehouse:view', 'warehouse:inventory:view',
    'archives:view', 'archives:product:view'
  ],
  
  // 财务人员 - 财务相关权限
  'finance': [
    'finance:*', 'report:view', 'report:standard:view',
    'pivot:view', 'pivot:analysis:view'
  ],
  
  // 仓库管理员 - 仓库相关权限
  'warehouse_manager': [
    'warehouse:*', 'purchase:view', 'purchase:receiving:view',
    'archives:view', 'archives:product:view'
  ]
}

/**
 * 检查用户是否有访问路由的权限
 * @param {string} path 路由路径
 * @param {object} userInfo 用户信息
 * @returns {boolean} 是否有权限
 */
export function hasRoutePermission(path, userInfo) {
  // 如果是白名单路由，直接允许访问
  if (whiteList.includes(path)) {
    return true
  }
  
  // 如果用户未登录，拒绝访问
  if (!userInfo || !userInfo.role) {
    return false
  }
  
  // 获取用户角色
  const userRole = userInfo.role
  
  // 系统管理员拥有所有权限
  if (userRole === 'admin') {
    return true
  }
  
  // 获取角色对应的权限列表
  const rolePermissions = roleRoutes[userRole] || []
  
  // 检查是否有通配符权限
  if (rolePermissions.includes('*')) {
    return true
  }
  
  // 获取路由需要的权限
  const requiredPermissions = getRoutePermissions(path)
  
  // 如果路由不需要特殊权限，允许访问
  if (!requiredPermissions || requiredPermissions.length === 0) {
    return true
  }
  
  // 检查用户是否拥有所需权限
  return requiredPermissions.some(permission => {
    return rolePermissions.some(rolePermission => {
      // 检查完全匹配
      if (rolePermission === permission) {
        return true
      }
      
      // 检查通配符匹配
      if (rolePermission.endsWith(':*')) {
        const prefix = rolePermission.slice(0, -2)
        return permission.startsWith(prefix + ':')
      }
      
      return false
    })
  })
}

/**
 * 获取路由所需的权限
 * @param {string} path 路由路径
 * @returns {array} 权限列表
 */
function getRoutePermissions(path) {
  // 精确匹配
  if (permissionRoutes[path]) {
    return permissionRoutes[path]
  }
  
  // 模糊匹配（匹配父路由）
  const pathSegments = path.split('/').filter(Boolean)
  for (let i = pathSegments.length; i > 0; i--) {
    const parentPath = '/' + pathSegments.slice(0, i).join('/')
    if (permissionRoutes[parentPath]) {
      return permissionRoutes[parentPath]
    }
  }
  
  return []
}

/**
 * 路由前置守卫
 * @param {object} to 目标路由
 * @param {object} from 来源路由
 * @param {function} next 导航函数
 */
export function beforeEachGuard(to, from, next) {
  const userStore = useUserStore()
  
  // 设置页面标题
  if (to.meta && to.meta.title) {
    document.title = `${to.meta.title} - ERP管理系统`
  } else {
    document.title = 'ERP管理系统'
  }
  
  // 检查是否需要登录
  if (whiteList.includes(to.path)) {
    // 白名单路由直接放行
    next()
    return
  }
  
  // 检查用户是否已登录
  if (!userStore.isLoggedIn) {
    ElMessage.warning('请先登录')
    next('/login')
    return
  }
  
  // 检查路由权限
  if (!hasRoutePermission(to.path, userStore.userInfo)) {
    ElMessage.error('您没有访问该页面的权限')
    
    // 如果来源路由有效，返回来源路由，否则跳转到首页
    if (from.path && from.path !== '/login') {
      next(false)
    } else {
      next('/dashboard')
    }
    return
  }
  
  // 权限检查通过，允许访问
  next()
}

/**
 * 路由后置守卫
 * @param {object} to 目标路由
 * @param {object} from 来源路由
 */
export function afterEachGuard(to, from) {
  // 页面加载完成后的处理
  // 可以在这里添加页面访问统计、用户行为追踪等逻辑
  
  // 滚动到页面顶部
  window.scrollTo(0, 0)
  
  // 记录页面访问日志（可选）
  if (process.env.NODE_ENV === 'development') {
    console.log(`页面访问: ${from.path} -> ${to.path}`)
  }
}

/**
 * 获取用户可访问的菜单列表
 * @param {object} userInfo 用户信息
 * @returns {array} 菜单列表
 */
export function getAccessibleMenus(userInfo) {
  if (!userInfo || !userInfo.role) {
    return []
  }
  
  const allMenus = [
    {
      path: '/dashboard',
      title: '系统首页',
      icon: 'House',
      permission: null // 所有登录用户都可访问
    },
    {
      path: '/users',
      title: '用户管理',
      icon: 'User',
      permission: ['user:view'],
      children: [
        { path: '/users/list', title: '用户列表', permission: ['user:view'] },
        { path: '/users/roles', title: '角色管理', permission: ['role:view'] }
      ]
    },
    {
      path: '/hr',
      title: '人力资源',
      icon: 'Avatar',
      permission: ['hr:view'],
      children: [
        { path: '/hr/employees', title: '员工档案', permission: ['hr:employee:view'] },
        { path: '/hr/attendance', title: '考勤管理', permission: ['hr:attendance:view'] },
        { path: '/hr/salary', title: '薪资管理', permission: ['hr:salary:view'] }
      ]
    },
    {
      path: '/purchase',
      title: '采购管理',
      icon: 'ShoppingCart',
      permission: ['purchase:view'],
      children: [
        { path: '/purchase/suppliers', title: '供应商管理', permission: ['purchase:supplier:view'] },
        { path: '/purchase/orders', title: '采购订单', permission: ['purchase:order:view'] },
        { path: '/purchase/receiving', title: '采购入库', permission: ['purchase:receiving:view'] }
      ]
    },
    {
      path: '/warehouse',
      title: '仓库管理',
      icon: 'Box',
      permission: ['warehouse:view'],
      children: [
        { path: '/warehouse/inventory', title: '库存查询', permission: ['warehouse:inventory:view'] },
        { path: '/warehouse/inbound', title: '入库管理', permission: ['warehouse:inbound:view'] },
        { path: '/warehouse/outbound', title: '出库管理', permission: ['warehouse:outbound:view'] },
        { path: '/warehouse/stocktaking', title: '盘点管理', permission: ['warehouse:stocktaking:view'] }
      ]
    },
    {
      path: '/sales',
      title: '销售管理',
      icon: 'Sell',
      permission: ['sales:view'],
      children: [
        { path: '/sales/customers', title: '客户管理', permission: ['sales:customer:view'] },
        { path: '/sales/orders', title: '销售订单', permission: ['sales:order:view'] },
        { path: '/sales/pos', title: '收银管理', permission: ['sales:pos:view'] }
      ]
    },
    {
      path: '/finance',
      title: '财务管理',
      icon: 'Money',
      permission: ['finance:view'],
      children: [
        { path: '/finance/accounts', title: '会计科目', permission: ['finance:account:view'] },
        { path: '/finance/vouchers', title: '凭证管理', permission: ['finance:voucher:view'] },
        { path: '/finance/reports', title: '财务报表', permission: ['finance:report:view'] }
      ]
    },
    {
      path: '/archives',
      title: '基础档案',
      icon: 'Files',
      permission: ['archives:view'],
      children: [
        { path: '/archives/products', title: '商品档案', permission: ['archives:product:view'] },
        { path: '/archives/bom', title: 'BOM管理', permission: ['archives:bom:view'] }
      ]
    },
    {
      path: '/reports',
      title: '报表中心',
      icon: 'Document',
      permission: ['report:view'],
      children: [
        { path: '/reports/standard', title: '标准报表', permission: ['report:standard:view'] },
        { path: '/reports/custom', title: '自定义报表', permission: ['report:custom:view'] }
      ]
    },
    {
      path: '/pivot',
      title: '透视分析',
      icon: 'TrendCharts',
      permission: ['pivot:view'],
      children: [
        { path: '/pivot/analysis', title: '多维分析', permission: ['pivot:analysis:view'] },
        { path: '/pivot/drill', title: '数据钻取', permission: ['pivot:drill:view'] }
      ]
    },
    {
      path: '/ai',
      title: 'AI分析',
      icon: 'MagicStick',
      permission: ['ai:view'],
      children: [
        { path: '/ai/prediction', title: '智能预测', permission: ['ai:prediction:view'] },
        { path: '/ai/anomaly', title: '异常检测', permission: ['ai:anomaly:view'] }
      ]
    },
    {
      path: '/lowcode',
      title: '低代码开发',
      icon: 'Operation',
      permission: ['lowcode:view'],
      children: [
        { path: '/lowcode/forms', title: '表单设计器', permission: ['lowcode:form:view'] },
        { path: '/lowcode/workflows', title: '流程设计器', permission: ['lowcode:workflow:view'] }
      ]
    },
    {
      path: '/datamodel',
      title: '数据模型',
      icon: 'Connection',
      permission: ['datamodel:view'],
      children: [
        { path: '/datamodel/entities', title: '实体定义', permission: ['datamodel:entity:view'] },
        { path: '/datamodel/relations', title: '关系配置', permission: ['datamodel:relation:view'] }
      ]
    },
    {
      path: '/system',
      title: '系统配置',
      icon: 'Setting',
      permission: ['system:view'],
      children: [
        { path: '/system/settings', title: '参数设置', permission: ['system:setting:view'] },
        { path: '/system/monitor', title: '系统监控', permission: ['system:monitor:view'] }
      ]
    }
  ]
  
  // 过滤用户有权限访问的菜单
  return filterMenusByPermission(allMenus, userInfo)
}

/**
 * 根据权限过滤菜单
 * @param {array} menus 菜单列表
 * @param {object} userInfo 用户信息
 * @returns {array} 过滤后的菜单列表
 */
function filterMenusByPermission(menus, userInfo) {
  return menus.filter(menu => {
    // 检查菜单权限
    if (menu.permission && !hasMenuPermission(menu.permission, userInfo)) {
      return false
    }
    
    // 创建菜单副本以避免修改原始对象
    const menuCopy = { ...menu }
    
    // 过滤子菜单
    if (menuCopy.children && Array.isArray(menuCopy.children)) {
      menuCopy.children = filterMenusByPermission(menuCopy.children, userInfo)
      // 如果所有子菜单都被过滤掉，则隐藏父菜单
      if (menuCopy.children.length === 0 && menuCopy.permission) {
        return false
      }
    }
    
    return true
  }).map(menu => {
    // 返回处理后的菜单副本
    const menuCopy = { ...menu }
    if (menuCopy.children && Array.isArray(menuCopy.children)) {
      menuCopy.children = filterMenusByPermission(menuCopy.children, userInfo)
    }
    return menuCopy
  })
}

/**
 * 检查菜单权限
 * @param {array} requiredPermissions 所需权限
 * @param {object} userInfo 用户信息
 * @returns {boolean} 是否有权限
 */
function hasMenuPermission(requiredPermissions, userInfo) {
  if (!userInfo || !userInfo.role) {
    return false
  }
  
  const userRole = userInfo.role
  
  // 系统管理员拥有所有权限
  if (userRole === 'admin') {
    return true
  }
  
  // 获取角色对应的权限列表
  const rolePermissions = roleRoutes[userRole] || []
  
  // 检查是否有通配符权限
  if (rolePermissions.includes('*')) {
    return true
  }
  
  // 检查用户是否拥有所需权限
  return requiredPermissions.some(permission => {
    return rolePermissions.some(rolePermission => {
      // 检查完全匹配
      if (rolePermission === permission) {
        return true
      }
      
      // 检查通配符匹配
      if (rolePermission.endsWith(':*')) {
        const prefix = rolePermission.slice(0, -2)
        return permission.startsWith(prefix + ':')
      }
      
      return false
    })
  })
}